'use strict';
const http = require("http"), fs = require('fs'), url = require("url");

process.on('uncaughtException', function(err) {
  //console.log('uncaughtException: ', err.stack);
  const loger = require("./module/loger").init();
  loger.error('uncaughtException: ', err.stack);
});

global.LOG = require("./module/loger").init();

let hconfig = require("./config/http");
let lport = {};
for(let k in hconfig)
{
    let port = 0;
    if(k.indexOf(":") != -1)
    {
        let ar = k.split(":");
        port = ar[1];
    }
    else
        port = 80;
    if(lport[port]) continue;
    if(port > 0)
    {
        lport[port] = 1;
        if(hconfig[k].debug){
            let ald = require("./module/autoreload");
            ald.watch(hconfig[k].key);
        }

        let server = http.createServer(function(request, response){
			hconfig = require("./config/http");
            //console.log('httpreq', req.method);

            if(!(request.headers.host in hconfig))
            {
                let loger = require("./module/loger").init();
                loger.error(request.headers.host, request.method, request.url);
                response.statusCode = 404;
                response.end("not find site");
                return;
            }
            let site = request.SITE = hconfig[request.headers.host];
            if(typeof(site) == "string") site = request.SITE = hconfig[site];
			request.LOG = require("./module/loger").init(site.key);
            request.LOG.info(request.headers.host, request.method, request.url);
            request.PUBFUN = require("./module/pubfun");
            request.GET = url.parse(request.url, true);

            for(let i=0;i<site.route.length;i++)
            {
                for(let j=0;j<site.route[i].url.length;j++)
                {
                    let s = new RegExp(site.route[i].url[j], 'i');
                    if(request.GET.pathname.search(s) != -1)
                    {
                        function rtfun(rt, mi, rq, rs)
                        {
                            if(mi >= rt.mod.length) return;

                            let runop = require(rt.mod[mi]);
                            runop(rq, rs, (v)=>{
                                if(v === false) return;
                                if(!rs.DATA && v) rs.DATA = v;
                                //console.log(typeof rs.DATA, typeof v);
                                rtfun(rt, mi+1, rq, rs);
                            }); 
                        }
                        rtfun(site.route[i], 0, request, response);
                        return;
                    }
                }
            }
            let runop = require("./module/html");
            runop(request, response);
        });

        server.on('error', function(e){
            var loger = require("./module/loger").init();
            loger.error("server error ", e);
            fs.appendFile("runhttp.log", new Date().toLocaleString() + "server error " + e + "\r\n", ()=>{});
        });

        server.listen(port, function() { //'listening' listener
            console.log('server bound', port);
            fs.appendFile("runhttp.log", new Date().toLocaleString() + " " + port + "\r\n", ()=>{});
        });
    }
}

//------------------------------------------------------------------------------------------------------------
//命令行处理
const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});
rl.on('line', function(chunk) {
	if (chunk !== null) {
		var da = chunk.toString('utf8', 0, chunk.length - 2).split(' ');
		if(da[0] == 'reload'){
			//如\login\ext.js
			if(require.cache[__dirname + da[1]]){
				var md = require(__dirname + da[1]);
				if(md.destroy){
					md.destroy();
				}
				delete require.cache[__dirname + da[1]];
				console.log(da[1] + ' cache is delete');
				require(__dirname + da[1]);
			}else{
				console.log(da[1] + ' not cache');
			}
		}else if(da[0] == 'eval'){
            da = da.slice(1);
            eval(da.join(" "));
        }
	}
});